package com.suray.wcs.service.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.suray.commin.annotation.DataScope;
import com.suray.commin.core.entity.RoleDB;
import com.suray.commin.core.redis.RedisCache;
import com.suray.commin.core.utils.*;
import com.suray.wcs.service.execption.CaptchaException;
import com.suray.wcs.service.execption.CaptchaExpireException;
import com.suray.wcs.service.execption.CustomException;
import com.suray.wcs.service.execption.UserPasswordNotMatchException;
import com.suray.wcs.service.manager.AsyncManager;
import com.suray.wcs.service.manager.factory.AsyncFactory;
import com.suray.commin.core.pojo.LoginUser;
import com.suray.commin.core.entity.UserDB;
import com.suray.wcs.service.system.entity.UserRoleDB;
import com.suray.wcs.service.system.mapper.*;
import com.suray.wcs.service.system.service.ISysConfigService;
import com.suray.wcs.service.system.service.IUserDBService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserDBServiceImpl extends ServiceImpl<UserDBMapper, UserDB> implements IUserDBService {
    @Autowired
    private ISysConfigService configService;

    @Autowired
    private UserDBMapper userDBMapper;

    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private UserRoleDBMapper userRoleDBMapper;

    @Autowired
    private RoleDBMapper roleDBMapper;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    @Override
    public String login(String username, String password, String code, String uuid) {
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }
        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new CustomException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成token
        return tokenService.createToken(loginUser);
    }


    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public UserDB selectUserByUserName(String userName) {
        return userDBMapper.selectUserByUserName(userName);
    }

    @Override
    public String importUser(List<UserDB> userList, boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new CustomException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (UserDB user : userList) {
            try {
                // 验证是否存在这个用户
                UserDB u = userDBMapper.selectUserByUserName(user.getUserName());
                if (StringUtils.isNull(u)) {
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    this.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                } else if (isUpdateSupport) {
                    user.setUpdateBy(operName);
                    this.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }


    /**
     * 根据用户名查询用户
     *
     * @param opername 用户名
     * @author yuy
     */
    @Override
    public UserDB findByUserName(String opername) {
        LambdaQueryWrapper<UserDB> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserDB::getUserName, opername);
        return getOne(queryWrapper);
    }

    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<UserDB> selectUserList(UserDB user) {
        return userDBMapper.selectUserList(user);
    }



    /**
     * 分页查询
     *
     * @param searchModel
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public IPage<UserDB> getUsers(UserDB searchModel, Integer pageNum, Integer pageSize) {
        Page<UserDB> userDBPage = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<UserDB> queryWrapper = new LambdaQueryWrapper();
        if (!StringUtils.isEmpty(searchModel.getRoleIds())) {
            queryWrapper.eq(UserDB::getRoleIds, searchModel.getRoleIds());
        }
//        if (!StringUtils.isEmpty(searchModel.())) {
//            queryWrapper.eq(UserDB::getZhiWei, searchModel.getZhiWei());
//        }
        if (!StringUtils.isEmpty(searchModel.getUserName())) {
            queryWrapper.like(UserDB::getUserName, searchModel.getUserName());
        }
        return userDBMapper.selectPage(userDBPage, queryWrapper);
    }


    @Override
    public boolean updateUserByID(UserDB updateModel, Long userId) {
//        updateModel.setUpdateId(userId);
//        updateModel.setUpdateYmd(DateUtil.getNow());
        return this.updateById(updateModel);
    }

    @Override
    public UserDB getUserByNameAndPass(String operatorName, String password) {
        LambdaQueryWrapper<UserDB> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserDB::getUserName, operatorName).eq(UserDB::getPassword, password);
        return getOne(queryWrapper);
    }

    @Override
    public UserDB getByUserId(String getUserId) {
        LambdaQueryWrapper<UserDB> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserDB::getUserId, getUserId);
        return getOne(queryWrapper);
    }

    @Override
    public UserDB getByUserName(String userName) {
        LambdaQueryWrapper<UserDB> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserDB::getUserName, userName);
        return getOne(queryWrapper);
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param userName 用户名称
     * @return 结果
     */
    @Override
    public String checkUserNameUnique(String userName) {
        int count = userDBMapper.checkUserNameUnique(userName);
        if (count > 0) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验电话号码是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkPhoneUnique(UserDB user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        UserDB info = userDBMapper.checkPhoneUnique(user.getPhonenumber());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkEmailUnique(UserDB user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        UserDB info = userDBMapper.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertUser(UserDB user) {
        // 新增用户信息
        int rows = userDBMapper.insertUser(user);
        // 新增用户与角色关联
        insertUserRole(user);
        return rows;
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(UserDB user) {
        if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin()) {
            throw new CustomException("不允许操作超级管理员用户");
        }
    }

    /**
     * 修改用户状态
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserStatus(UserDB user) {
        return userDBMapper.updateUser(user);
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserByIds(Long[] userIds) {
        for (Long userId : userIds) {
            checkUserAllowed(new UserDB(userId));
        }
        //  删除用户与角色关联
        userRoleDBMapper.deleteUserRole(userIds);
        return userDBMapper.deleteUserByIds(userIds);
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUser(UserDB user) {
        Long userId = user.getUserId();
        // 删除用户与角色关联
        userRoleDBMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色关联
        insertUserRole(user);
        return userDBMapper.updateUser(user);
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(UserDB user) {
        Long[] roles = user.getRoleIds();
        if (StringUtils.isNotNull(roles)) {
            // 新增用户与角色管理
            List<UserRoleDB> list = new ArrayList<UserRoleDB>();
            for (Long roleId : roles) {
                UserRoleDB ur = new UserRoleDB();
                ur.setUserId(user.getUserId());
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0) {
                userRoleDBMapper.batchUserRole(list);
            }
        }
    }

    /**
     * 重置用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(UserDB user) {
        return userDBMapper.updateUser(user);
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName)
    {
        List<RoleDB> list = roleDBMapper.selectRolesByUserName(userName);
        StringBuffer idsStr = new StringBuffer();
        for (RoleDB role : list)
        {
            idsStr.append(role.getRoleName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString()))
        {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(UserDB user)
    {
        return userDBMapper.updateUser(user);
    }

    /**
     * 重置用户密码
     *
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(String userName, String password)
    {
        return userDBMapper.resetUserPwd(userName, password);
    }

    /**
     * 修改用户头像
     *
     * @param userName 用户名
     * @param avatar 头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(String userName, String avatar)
    {
        return userDBMapper.updateUserAvatar(userName, avatar) > 0;
    }
}
